//
//  DownloadManager.m
//  ZYYD
//
//  Created by yuzhou on 12-8-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DownloadManager.h"
#import "DownloadInfo.h"
#import "Constant.h"
#import "DownloadDelegate.h"

@interface DownloadManager ()

@property (nonatomic,retain) NSDictionary *pausedDic;//因为切换到3G而被取消的下载

@end

@implementation DownloadManager
@synthesize allDownload;

static DownloadManager *downloadManager;

+ (id)defaultManager
{
    if(downloadManager == nil){
        downloadManager = [[DownloadManager alloc] init];
    }
    return downloadManager;
}

- (id)init
{
    self = [super init];
    if(self){
        queue = [[ASINetworkQueue alloc] init];
        [queue setShowAccurateProgress:YES];
        [queue setMaxConcurrentOperationCount:1];
        [queue go];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil];
        reachability = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
        [reachability startNotifier];
    }
    return self;
}

#pragma mark 下载操作
- (void)downloadBook:(NSDictionary *)dic
{
    if ([self indexOfID:[dic valueForKey:@"subitem_id"]] != -1) {
        return;
    }
    DownloadInfo *downloadInfo = [[[DownloadInfo alloc] init] autorelease];
    downloadInfo.infoDic = dic;
    [self.allDownload insertObject:downloadInfo atIndex:[self positionOfDownloadInfo:dic]];
    [self save];
    
    if (queue.operations.count == 0) {
        [self download:dic];
    }
}

- (void)download:(NSDictionary *)dic
{
    NSString *itemid = [dic valueForKey:@"item_id"];
    NSString *subitemid = [dic valueForKey:@"subitem_id"];
    if(![[NSFileManager defaultManager] createDirectoryAtPath:FolderPath(itemid) withIntermediateDirectories:YES attributes:nil error:nil]){
        return;
    }
    
    NSString *urlString = [[dic valueForKey:@"file_name"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    DownloadDelegate *downloadDelegate = [[DownloadDelegate alloc] init];
    downloadDelegate.infoDic = dic;
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:itemid,@"item_id",subitemid,@"subitem_id", nil];
    [request setDownloadDestinationPath:DownloadPath(itemid, subitemid)];
    [request setAllowResumeForFileDownloads:YES];
    [request setTemporaryFileDownloadPath:TempPath(itemid, subitemid)];
    [request setDelegate:downloadDelegate];
    [request setDownloadProgressDelegate:downloadDelegate];
    [request setShouldContinueWhenAppEntersBackground:YES];
    [queue addOperation:request];
    
    self.downloadingDic = dic;
    waitingForWifi = NO;
}

- (void)downloadNext
{
    NSString *itemid = [self.downloadingDic valueForKey:@"item_id"];
    NSString *subitemid = [self.downloadingDic valueForKey:@"subitem_id"];
    int index = [self indexOfID:subitemid];
    if (index >= 0) {
        for (int i = index+1;i < self.allDownload.count;i++) {
            DownloadInfo *downloadInfo = [self.allDownload objectAtIndex:i];
            if (!downloadInfo.downloaded && [[downloadInfo.infoDic valueForKey:@"item_id"] isEqualToString:itemid]) {
                [self download:downloadInfo.infoDic];
                return;
            }
        }
    }
    for (DownloadInfo *downloadInfo in self.allDownload) {
        if (!downloadInfo.downloaded) {
            [self download:downloadInfo.infoDic];
            return;
        }
    }
    [[DownloadManager defaultManager] setDownloadingDic:nil];
    
    ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"已完成所有下载任务"] autorelease];
    [promptView show];
}

- (void)cancelDownload
{
    for(ASIHTTPRequest *request in queue.operations){
        [request clearDelegatesAndCancel];
        [request.delegate release];
    }
    self.downloadingDic = nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateDownloadStatus object:nil];
}

- (void)cancelDownload:(NSString *)subitem_id
{
    if ([[_downloadingDic objectForKey:@"subitem_id"] isEqualToString:subitem_id]) {
        [self cancelDownload];
        [self deleteDownloadInfo:subitem_id];
        [self downloadNext];
    }
    else {
        [self deleteDownloadInfo:subitem_id];
    }
    [self save];
}

- (void)redownloadWithID:(NSString *)subitem_id
{
    int index = [self indexOfID:subitem_id];
    DownloadInfo *downloadInfo = [self.allDownload objectAtIndex:index];
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:downloadInfo.infoDic];
    [self download:dic];
}

- (void)deleteDownloadInfo:(NSString *)subitem_id
{
    int index = [self indexOfID:subitem_id];
    [self.allDownload removeObjectAtIndex:index];
}

- (void)deleteBookID:(NSString *)item_id
{
    NSError *error = [[NSError new] autorelease];
    if ([[NSFileManager defaultManager] removeItemAtPath:FolderPath(item_id) error:&error]) {
        NSArray *chapters = [self getDownloadedChapterByID:item_id];
        for (NSDictionary *chapter in chapters) {
            [self deleteDownloadInfo:[chapter objectForKey:@"subitem_id"]];
        }
        [self save];
    }
}

- (void)save
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.allDownload];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:kAllDownload];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark 下载完成状态
- (BOOL)isDownloading:(NSString *)subitem_id
{
    return [[self.downloadingDic valueForKey:@"subitem_id"] isEqualToString:subitem_id];
}

- (BOOL)isDownloaded:(NSString *)subitem_id
{
    for(DownloadInfo *downloadInfo in self.allDownload){
        if([[downloadInfo.infoDic valueForKey:@"subitem_id"] isEqualToString:subitem_id]){
            if (downloadInfo.downloaded) {
                return YES;
            }
            else {
                return NO;
            }
        }
    }
    return NO;
}

- (DownloadInfo *)downloadInfoOfID:(NSString *)subitem_id
{
    int index = [self indexOfID:subitem_id];
    if( index >= 0){
        return [self.allDownload objectAtIndex:index];
    }
    return nil;
}

- (int)indexOfID:(NSString *)subitem_id
{
    for(DownloadInfo *info in self.allDownload){
        if([[info.infoDic valueForKey:@"subitem_id"] isEqualToString:subitem_id]){
            return [self.allDownload indexOfObject:info];
        }
    }
    return -1;
}

- (int)positionOfDownloadInfo:(NSDictionary *)dic
{
    NSString *itemid = [dic valueForKey:@"item_id"];
    NSString *subitemid = [dic valueForKey:@"subitem_id"];
    BOOL hasBrotherChapter;
    for (DownloadInfo *downloadInfo in self.allDownload) {
//        NSLog(@"id2:%@",[downloadInfo.infoDic valueForKey:@"item_id"]);
        if ([[downloadInfo.infoDic valueForKey:@"item_id"] isEqualToString:itemid]) {
            hasBrotherChapter = YES;
//            NSLog(@"找到兄弟章节");
//            NSLog(@"sub1:%d sub2:%d",[subitemid intValue],[[downloadInfo.infoDic valueForKey:@"subitem_id"] intValue]);
            if ([[downloadInfo.infoDic valueForKey:@"subitem_id"] intValue] > [subitemid intValue]) {
//                NSLog(@"找到后面的章节，得到位置");
                return [self.allDownload indexOfObject:downloadInfo];
            }
        }
        else {
//            NSLog(@"发现新书章节");
            if (hasBrotherChapter) {
//                NSLog(@"已有兄弟章节，得到位置");
                return [self.allDownload indexOfObject:downloadInfo];
            }
        }
    }
    if (hasBrotherChapter) {
//        NSLog(@"插在最后");
        return self.allDownload.count;
    }
//    NSLog(@"没发现兄弟章节");
    return 0;
}

#pragma mark 获取集合
- (NSMutableArray *)allDownload
{
    if(allDownload != nil){
        //        NSLog(@"allDownload:%@",allDownload);
        return allDownload;
    }
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kAllDownload];
    if (data) {
        allDownload = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    if(allDownload == nil){
        allDownload = [NSArray array];
    }
    allDownload = [[NSMutableArray alloc] initWithArray:allDownload];
    return allDownload;
}

- (NSArray *)getDownloading
{
    NSMutableArray *downloadingArray = [NSMutableArray array];
    for (DownloadInfo *downloadInfo in self.allDownload) {
        if (downloadInfo.downloaded == NO) {
            [downloadingArray addObject:downloadInfo];
        }
    }
    return downloadingArray;
}

- (NSArray *)getDownloadedID
{
    NSMutableArray *downloadedArray = [NSMutableArray array];
    for (DownloadInfo *downloadInfo in self.allDownload) {
        if (downloadInfo.downloaded == YES) {
            NSString *item_id = [downloadInfo.infoDic valueForKey:@"item_id"];
            if (![downloadedArray containsObject:item_id]) {
                [downloadedArray addObject:item_id];
            }
        }
    }
    return downloadedArray;
}

- (NSArray *)getDownloadedChapterByID:(NSString *)item_id
{
    NSMutableArray *downloadedChapterArray = [NSMutableArray array];
    for (DownloadInfo *downloadInfo in self.allDownload) {
        if (downloadInfo.downloaded == YES && [[downloadInfo.infoDic valueForKey:@"item_id"] isEqualToString:item_id]) {
            [downloadedChapterArray addObject:downloadInfo.infoDic];
        }
    }
    return downloadedChapterArray;
}

- (NSArray *)filterWithKeyword:(NSString *)keyword
{
    NSMutableArray *array = [NSMutableArray array];
    for (DownloadInfo *downloadInfo in self.allDownload){
        if ([[downloadInfo.infoDic valueForKey:@"item_name"] rangeOfString:keyword].location != NSNotFound) {
            [array addObject:downloadInfo];
        }
    }
    return array;
}

#pragma mark 下载状态
- (void)reachabilityChanged
{
    switch ([reachability currentReachabilityStatus]) {
        case NotReachable:
            // 没有网络连接
            NSLog(@"没有网络连接");
            ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"网络连接断开"] autorelease];
            [promptView show];
            break;
        case ReachableViaWWAN:
            // 使用3G网络
        {
            NSLog(@"使用3G网络");
            if (!self.WWANDownloadEnable) {
                NSLog(@"切换到3G，不允许3G下载，暂停下载！");
                ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"wifi断开，下载已暂停"] autorelease];
                [promptView show];
                self.pausedDic = _downloadingDic;
                [self cancelDownload];
                waitingForWifi = YES;
            }
        }
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
        {
            NSLog(@"使用WiFi网络");
            if (waitingForWifi && _pausedDic) {
                ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"wifi开启，继续下载"] autorelease];
                [promptView show];
                [self download:_pausedDic];
            }
        }
            break;
        default:
            break;
    }
    
    if ([self isConnectionEnable]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kConnectionEnable object:nil];
    }
}

- (BOOL)isConnectionEnable
{
    return [reachability isReachable];
}

- (BOOL)isWifiEnable
{
    return [reachability isReachableViaWiFi];
}

- (BOOL)isWWANEnable
{
    return [reachability isReachableViaWWAN];
}

- (BOOL)WWANDownloadEnable
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:kDownloadViaWWAN];
}

- (void)setWWANDownloadEnable:(BOOL)WWANDownloadEnable
{
    [[NSUserDefaults standardUserDefaults] setBool:WWANDownloadEnable forKey:kDownloadViaWWAN];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (WWANDownloadEnable) {
        
    }
    else {//如果当前正在用2G/3G网络，则停止下载
        if ([self isWWANEnable] && queue.operations.count > 0) {
            NSLog(@"更改设置后，不允许3G下载，暂停下载！");
            self.pausedDic = _downloadingDic;
            [self cancelDownload];
            waitingForWifi = YES;
        }
    }
}

- (void)deletePdf:(NSString *)id
{
    int index = [self indexOfID:id];
    if (index >= 0){
        DownloadInfo *downloadInfo = [self.allDownload objectAtIndex:index];
        if (!downloadInfo.downloaded){
            [self cancelDownload];
        }
        [self deletePdfFile:id];
        [self deleteDownloadInfo:id];
        
        //        [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateShelfGridViewWithDelete object:[NSNumber numberWithInt:index]];
    }
}

- (void)deletePdfFile:(NSString *)id
{
    NSString *folferPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Library/Caches/pdf/%@",id]];
    [[NSFileManager defaultManager] removeItemAtPath:folferPath error:nil];
}



- (void)dealloc
{
    [reachability stopNotifier];
    [reachability release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [queue release];
    [_pausedDic release];
    [super dealloc];
}
@end
